#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(char* s)
{
    cout << "Usage: " << s << " ip port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) return 1;

    struct sockaddr_in peer;
    peer.sin_family = AF_INET;
    peer.sin_port = htons(atoi(argv[2]));
    peer.sin_addr.s_addr = inet_addr(argv[1]);

    while (1)
    {
    #define NUM 128
        printf("Clinet# ");
        fflush(stdout);
        char buf[NUM] = {0};
        read(0, buf, NUM - 1);

        sendto(sock, buf, sizeof(buf), 0, (sockaddr*)&peer, sizeof(peer));

        struct sockaddr_in si;
        char text[1024] = {0};
        socklen_t len = sizeof(si);
        ssize_t sz = recvfrom(sock, text, 1023, 0, (sockaddr*)&si, &len);
        if (sz > 0)
        {
            text[sz] = 0;
            cout << "Shell# " << text << endl; 
        }
        else if (sz == 0)
        {
            cout << "对端关闭" << endl;
            return 2;
        }
        else
        {
            return 3;
        }
    }
    return 0;
}